<template>
  <div class="custom-tabbar" :class="{ 'theme-dark': isDarkTheme }" :style="tabbarStyles">
    <div 
      v-for="(item, index) in tabList" 
      :key="index"
      class="tab-item"
      :class="{ 'active': currentPath === item.pagePath }"
      @click="switchTab(item)"
    >
      <div class="tab-icon-wrapper">
        <span class="tab-icon-text">{{ item.icon }}</span>
      </div>
      <span class="tab-text" :style="textStyles">{{ item.text }}</span>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'CustomTabBar',
  props: {
    // 支持动态配置tabbar列表
    customTabList: {
      type: Array,
      default: null
    },
    // 主题切换支持
    theme: {
      type: String,
      default: 'light',
      validator: value => ['light', 'dark', 'purple'].includes(value)
    }
  },
  data() {
    return {
      // 默认tabbar配置，从pages.json中提取
      defaultTabList: [
        {
          pagePath: "pages/main/index",
          icon: "👤",
          text: "人物"
        },
        {
          pagePath: "pages/adventure/index",
          icon: "🗺️",
          text: "游历"
        },
        {
          pagePath: "pages/opportunity/index",
          icon: "🎯",
          text: "机遇"
        },
        {
          pagePath: "pages/market/index",
          icon: "🏪",
          text: "市场"
        },
        {
          pagePath: "pages/system/index",
          icon: "⚙️",
          text: "系统"
        }
      ],
      currentPath: ''
    }
  },
  computed: {
    ...mapGetters('theme', ['currentThemeConfig', 'currentTabbarConfig', 'isDarkTheme', 'routeState', 'errorLog']),
    
    // 使用自定义配置或默认配置
    tabList() {
      return this.customTabList || this.defaultTabList
    },
    
    // 动态tabbar样式
    tabbarStyles() {
      const config = this.currentTabbarConfig
      return {
        backgroundColor: config.backgroundColor,
        borderTopColor: config.borderColor
      }
    },
    
    // 动态文字样式
    textStyles() {
      const config = this.currentTabbarConfig
      return {
        color: config.color,
        '--selected-color': config.selectedColor
      }
    }
  },
  mounted() {
    // 初始化主题
    this.$store.dispatch('theme/initTheme')
    this.updateCurrentPath()
    // 监听路由变化
    window.addEventListener('hashchange', this.updateCurrentPath)
  },
  beforeDestroy() {
    window.removeEventListener('hashchange', this.updateCurrentPath)
  },
  methods: {
    // 更新当前路径
    updateCurrentPath() {
      let hash = window.location.hash.slice(1)
      
      // 移除开头的斜杠（如果有）
      if (hash.startsWith('/')) {
        hash = hash.slice(1)
      }
      
      const newPath = hash || 'pages/main/index'
      
      // 验证路径是否为有效的tabbar页面
      const validPaths = this.tabList.map(item => item.pagePath)
      
      // 尝试精确匹配
      let matchedPath = validPaths.find(path => path === newPath)
      
      // 如果精确匹配失败，尝试模糊匹配（去除查询参数和锚点）
      if (!matchedPath) {
        const cleanPath = newPath.split('?')[0].split('#')[0]
        matchedPath = validPaths.find(path => path === cleanPath || cleanPath.startsWith(path))
      }
      
      if (matchedPath) {
        this.currentPath = matchedPath
        // 同步路由状态到store
        this.$store.dispatch('theme/syncRouteState', {
          currentPath: matchedPath,
          timestamp: Date.now()
        })
      } else {
        // 如果不是tabbar页面，保持当前路径不变（而不是清空）
        // 这样可以确保即使在子页面，tabbar也能显示正确的active状态
        console.log('Not a tabbar page, keeping current path:', this.currentPath)
      }
    },
    
    // 切换tab
    switchTab(item) {
      try {
        // 添加点击反馈效果
        this.addClickFeedback(event.currentTarget)
        
        // 记录切换开始时间
        const switchStartTime = Date.now()
        
        // 同步路由状态
        this.$store.dispatch('theme/syncRouteState', {
          currentPath: item.pagePath,
          lastSwitchTime: switchStartTime,
          switchCount: (this.routeState.switchCount || 0) + 1
        })
        
        // 检查路径是否有效
        if (!item.pagePath) {
          this.handleTabError('invalid-path', '无效的页面路径', item)
          return
        }
        
        // 如果已经在当前页面，不需要跳转
        if (this.currentPath === item.pagePath) {
          return
        }
        
        // 执行页面跳转前的验证
        if (!this.validateTabSwitch(item)) {
          return
        }
        
        // 执行页面跳转
        const targetUrl = `/${item.pagePath}`
        
        // 使用uni.switchTab进行跳转
        if (window.uni && window.uni.switchTab) {
          window.uni.switchTab({
            url: targetUrl,
            success: () => {
              this.onTabSwitchSuccess(item, switchStartTime)
            },
            fail: (error) => {
              this.handleTabError('switch-failed', '页面跳转失败', item, error)
            }
          })
        } else {
          // 降级处理：直接修改hash
          this.fallbackNavigation(targetUrl, item, switchStartTime)
        }
        
      } catch (error) {
        this.handleTabError('exception', '页面切换异常', item, error)
      }
    },
    
    // 验证tab切换
    validateTabSwitch(item) {
      // 检查页面是否存在
      const validPaths = [
        'pages/main/index',
        'pages/adventure/index', 
        'pages/opportunity/index',
        'pages/market/index',
        'pages/system/index'
      ]
      
      if (!validPaths.includes(item.pagePath)) {
        this.handleTabError('invalid-page', '页面不存在', item)
        return false
      }
      
      // 检查网络状态（如果需要）
      if (!navigator.onLine) {
        this.handleTabError('network-error', '网络连接异常', item)
        return false
      }
      
      return true
    },
    
    // 处理tab切换成功
    onTabSwitchSuccess(item, switchStartTime) {
      const switchDuration = Date.now() - switchStartTime
      
      this.currentPath = item.pagePath
      
      // 更新路由状态
      this.$store.dispatch('theme/syncRouteState', {
        currentPath: item.pagePath,
        lastSwitchTime: Date.now(),
        switchDuration: switchDuration
      })
      
      // 触发成功事件
      this.$emit('tab-change', { 
        from: this.currentPath, 
        to: item.pagePath,
        timestamp: Date.now(),
        duration: switchDuration
      })
      
      // 同步状态到store
      this.$store.dispatch('theme/syncRouteState', {
        currentPath: item.pagePath,
        lastSwitchTime: Date.now(),
        switchCount: (this.$store.state.theme.switchCount || 0) + 1
      })
    },
    
    // 降级导航处理
    fallbackNavigation(targetUrl, item, switchStartTime) {
      try {
        window.location.hash = targetUrl
        this.onTabSwitchSuccess(item, switchStartTime)
      } catch (error) {
        this.handleTabError('fallback-failed', '降级导航失败', item, error)
      }
    },
    
    // 错误处理
    handleTabError(errorType, item, error = null) {
      this.isLoading = false
      
      const errorData = {
        type: errorType,
        item: item,
        error: error ? error.message || error : null,
        timestamp: Date.now(),
        userAgent: navigator.userAgent,
        url: window.location.href
      }
      
      // 记录错误到store
      this.$store.dispatch('theme/recordError', errorData)
      
      console.error(`标签页切换错误 [${errorType}]:`, errorData)
      
      // 显示用户友好的错误提示
      this.showErrorToast(errorType)
      
      // 触发错误事件
      this.$emit('tab-switch-error', errorData)
      
      // 尝试重试机制
      if (this.retryCount < this.maxRetries) {
        this.retryTabSwitch(item)
      }
    },
    
    // 显示错误提示
    showErrorToast(message) {
      if (window.uni && window.uni.showToast) {
        window.uni.showToast({
          title: message,
          icon: 'none',
          duration: 2000
        })
      } else {
        // 降级处理
        console.warn('Toast fallback:', message)
      }
    },
    
    // 添加点击反馈效果
    addClickFeedback(element) {
      element.classList.add('tab-clicking')
      setTimeout(() => {
        element.classList.remove('tab-clicking')
      }, 150)
    },
    
    // 重试机制
    retryTabSwitch(item, maxRetries = 3) {
      let retryCount = 0
      
      const attemptSwitch = () => {
        if (retryCount >= maxRetries) {
          this.handleTabError('retry-failed', `重试${maxRetries}次后仍然失败`, item)
          return
        }
        
        retryCount++
        setTimeout(() => {
          this.switchTab(item)
        }, 1000 * retryCount) // 递增延迟
      }
      
      attemptSwitch()
    }
  }
}
</script>

<style scoped>
/* ========== 武侠风格底部导航栏 - 参考图片样式 ========== */
.custom-tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 56px; /* 降低20%: 70 * 0.8 = 56 */
  background: rgba(248, 246, 241, 0.98);
  border-top: 3px solid #8b6f47; /* 边框也相应减少 */
  border-left: 2px solid #8b6f47;
  border-right: 2px solid #8b6f47;
  display: flex;
  align-items: center;
  justify-content: space-around;
  z-index: 1000;
  box-shadow: 0 -4px 16px rgba(139, 111, 71, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.5);
  font-family: "STSong", "Noto Serif SC", serif;
  backdrop-filter: blur(10px);
  padding: 6px 0 3px 0; /* 减少padding */
}

.custom-tabbar.theme-dark {
  background: rgba(74, 60, 42, 0.95);
  border-top-color: #8b6f47;
  border-left-color: #8b6f47;
  border-right-color: #8b6f47;
  box-shadow: 0 -6px 20px rgba(0, 0, 0, 0.5);
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4px 0; /* 减少padding */
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
  min-width: 50px; /* 减少最小宽度 */
}

.tab-item:hover {
  transform: translateY(-2px);
}

.tab-item::after {
  content: '';
  position: absolute;
  bottom: 2px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, #d4af37 0%, #ffd700 100%);
  transition: width 0.3s ease;
}

.tab-item.active::after {
  width: 24px;
}

.tab-icon-wrapper {
  width: 28px; /* 减少图标容器大小 */
  height: 28px;
  margin-bottom: 3px; /* 减少间距 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  border-radius: 6px;
  background: rgba(139, 111, 71, 0.05);
}

.tab-item.active .tab-icon-wrapper {
  transform: scale(1.15);
  background: rgba(139, 111, 71, 0.15);
  box-shadow: 0 2px 8px rgba(139, 111, 71, 0.2);
}

.tab-icon-text {
  font-size: 20px; /* 减少图标大小 */
  line-height: 1;
}

.tab-text {
  font-size: 11px; /* 减少文字大小 */
  color: #6b4f3b;
  white-space: nowrap;
  font-weight: 700;
  transition: all 0.3s ease;
  letter-spacing: 0.5px;
}

.tab-item.active .tab-text {
  color: #4a3c2a;
  font-weight: 700;
  text-shadow: 0 1px 2px rgba(139, 111, 71, 0.2);
}

.tab-item.active::after {
  width: 30px;
  height: 3px;
  bottom: 0;
}

.theme-dark .tab-text {
  color: #c4a57b;
}

.theme-dark .tab-item.active .tab-text {
  color: #d4af37;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .custom-tabbar {
    height: 50px; /* 移动端进一步降低 */
    padding: 4px 0 2px 0;
  }
  
  .tab-item {
    padding: 3px 0;
  }
  
  .tab-text {
    font-size: 9px;
  }
  
  .tab-icon-wrapper {
    width: 22px; /* 调整图标容器 */
    height: 22px;
    margin-bottom: 2px;
  }
  
  .tab-icon-text {
    font-size: 16px;
  }
}

/* 无障碍支持 */
.tab-item:focus {
  outline: 2px solid #667eea;
  outline-offset: 2px;
}
</style>